package com.archive.forum.controller;

import com.archive.forum.dto.CommentDTO;
import com.archive.forum.dto.PostDTO;
import com.archive.forum.enums.CommentTypeEnum;
import com.archive.forum.exception.CustomizeException;
import com.archive.forum.exception.ExceptionEnum;
import com.archive.forum.model.Post;
import com.archive.forum.model.User;
import com.archive.forum.service.CommentService;
import com.archive.forum.service.PostService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
public class PostController {
    @Autowired
    private PostService postService;
    @Autowired
    private CommentService commentService;
    //帖子详情
    @GetMapping("/post/{id}")
    public String post(@PathVariable(name = "id") Integer id, HttpServletRequest request,Model model) {
        User user =  (User) request.getSession().getAttribute("user");
        Integer userId = (user != null) ? user.getId() : null;
        PostDTO postDTO = postService.getById(id,userId);
        List<PostDTO> relatedPosts = postService.selectRelated(postDTO);
        List<CommentDTO> comments =  commentService.listByTargetId(id,CommentTypeEnum.POST,userId);
        postService.incView(id);
        model.addAttribute("post", postDTO);
        model.addAttribute("comments", comments);
        model.addAttribute("relatedPosts", relatedPosts);
        return "post";
    }
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deletePost(
            @PathVariable String id,
            HttpServletRequest request) {
        User user =  (User) request.getSession().getAttribute("user");
        Post post = postService.findById(id);
        if (user == null || !Objects.equals(user.getId(), post.getCreator())) {
            throw new  CustomizeException(ExceptionEnum.DELETE_FAIL);
        }
        try {

            //  执行删除
            postService.deletePost(id);

            return ResponseEntity.ok().body(Map.of(
                    "status", "success",
                    "message", "Post deleted successfully"
            ));

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "status", "error",
                            "message", "Failed to delete post: " + e.getMessage()
                    ));
        }
    }
}
